<template>
	<view class="container-station">
		<!-- 头部 -->
		<view class="header">
			<view class="header-title">站房列表</view>
			<view class="header-search">

				<uni-search-bar :focus="true" v-model="filterStationName" @input="selectStation" cancelButton="none"
					clearButton="none" bgColor="#fff">
				</uni-search-bar>
				<!-- <view class="icon-box">
						<image style="width: 30px;" src="../../static/lu_08.png" mode="" class="icon">
						</image>
					</view>
					<uni-easyinput type="text" @input="selectStation" v-model="filterStationName"
						class="inputField-station" placeholder="请输入站房名称" /> -->

				<button type="primary" class="header-btn" @click="gotoAddStation()">
					<view class="icon-box">
						<image style="width: 15px;" src="../../static/lu_03.png" alt="" class="icon" />
					</view>
					<view class="btn-text">
						新增站房
					</view>
				</button>


				<button type="primary" class="header-btn2" @click="importStation()">
					<view class="icon-box">
						<image style="width: 15px;" src="../../static/lu_05.png" alt="" class="icon" />
					</view>/
					<view class="btn-text">
						导入站房
					</view>
				</button>

			</view>
		</view>

	</view>

	<!-- Tab 栏 -->
	<div class="tab-container">
		<div v-for="(tab, index) in tabs" :key="index" :class="['tab', { 'active': activeTab === tab }]"
			@click="selectTab(tab)">
			{{ tab }}
		</div>
		<div class="tab-indicator" :style="{ left: `${(100 / tabs.length) * activeTabIndex}%` }"></div>
	</div>

	<!-- 内容区域 -->
	<view class="content-box">
		<view class="content" v-if="activeTab === '全部'">
			<view v-for="(card, index) in stationCard" :key="index"
				:class="['card', { 'odd': card.status=='1', 'even': card.status=='2' }]">
				<view class="flex">
					<view class="tag-box">
						<uni-tag type="success" v-if="card.status=='1'" text="已调试"></uni-tag>
						<uni-tag v-if="card.status=='2'" text="未调试"></uni-tag>
						<h3>{{card.stationName}}</h3>
					</view>
					<p>站房地址： {{ card.stationAddress }}</p>
				</view>
				<view class="flex-center">
					<button class="card-button" @click="goToStationDetail(card)">详情</button>
					<button class="card-button2" @click="deleteStation(card)">删除</button>
				</view>

			</view>
		</view>

		<view class="content" v-else-if="activeTab === '已调试'">
			<view v-for="(card, index) in debugedCard" :key="index"
				:class="['card', { 'odd': (index + 1) % 2 !== 0, 'even': (index + 1) % 2 === 0 }]">
				<view class="flex">
					<view class="tag-box">
						<uni-tag type="success" v-if="card.status=='1'" text="已调试"></uni-tag>
						<uni-tag v-if="card.status=='2'" text="未调试"></uni-tag>
						<h3>{{card.stationName}}</h3>
					</view>
					<p>站房地址： {{ card.stationAddress }}</p>
				</view>
				<view class="flex-center">
					<button class="card-button" @click="goToStationDetail(card)">详情</button>
					<button class="card-button2" @click="deleteStation(card)">删除</button>
				</view>
			</view>
		</view>
		<view class="content" v-else-if="activeTab === '未调试'">
			<view v-for="(card, index) in notDebugedCard" :key="index"
				:class="['card', { 'odd': (index + 1) % 2 !== 0, 'even': (index + 1) % 2 === 0 }]">
				<view class="flex">
					<view class="tag-box">
						<uni-tag type="success" v-if="card.status=='1'" text="已调试"></uni-tag>
						<uni-tag v-if="card.status=='2'" text="未调试"></uni-tag>
						<h3>{{card.stationName}}</h3>
					</view>
					<p>站房地址： {{ card.stationAddress }}</p>
				</view>
				<view class="flex-center">
					<button class="card-button" @click="goToStationDetail(card)">详情</button>
					<button class="card-button2" @click="deleteStation(card)">删除</button>
				</view>
			</view>
		</view>
	</view>

</template>

<script setup lang="ts">
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		stationList
	} from '@/data/station.js'
	import {
		uniIcons
	} from '@dcloudio/uni-ui';
	import {
		WEB_URL
	} from '../../config/global';
	import * as XLSX from 'xlsx';
	import {
		changeData,
		getJsonData
	} from '../../js_sdk/file';
	import {
		onShow
	} from '@dcloudio/uni-app';

	const filterStationName = ref('')
	// 定义全部内容的卡片数据
	const allCard = ref([])
	const stationCard = ref([])
	const debugedCard = ref([])
	const notDebugedCard = ref([])
	const uploadRef = ref()
	const selectedTabs = ref(0)
	// const filePath = ref('')
	const listStyles = ref({
		// 是否显示边框
		border: true,
		// 是否显示分隔线
		dividline: true,
		// 线条样式
		borderStyle: {
			width: 1,
			color: 'blue',
			radius: 2
		}
	})
	const tabs = ['全部', '已调试', '未调试'];
	const activeTab = ref(tabs[0]);
	const activeTabIndex = ref(0);

	const gotoAddStation = async () => {
		uni.navigateTo({
			url: '/pages/addStation/addStation'
		})
	}

	onShow(async () => {
		/**
		 * 读取站点数据
		 */
		let filePath = '_doc/test/station.json'
		let dataJson = await getJsonData(filePath)

		if (dataJson !== '') {
			stationCard.value = JSON.parse(dataJson);
			allCard.value = JSON.parse(dataJson);
			console.log('stationCard.value', stationCard.value);
			debugedCard.value = stationCard.value.filter((e) => e.status === 1)
			notDebugedCard.value = stationCard.value.filter((e) => e.status === 2)
		}

	})

	const selectStation = (text) => {
		if (selectedTabs.value === 0) {
			stationCard.value = allCard.value.filter((e) => {
				if (e.stationName.includes(text)) {
					return e
				}
			})

		}
		if (selectedTabs.value === 1) {
			debugedCard.value = allCard.value.filter((e) => {
				if (e.stationName.includes(text) && e.status === 1) {
					return e
				}
			})
		}
		if (selectedTabs.value === 2) {
			notDebugedCard.value = allCard.value.filter((e) => {
				if (e.stationName.includes(text) && e.status === 2) {
					return e
				}
			})
		}
	}

	const doDelete = async (card) => {
		let filePath = '_doc/test/station.json'
		let dataAfterDelete = stationCard.value.filter((e) => {
			return e.stationId !== card.stationId
		})
		const change = await changeData(filePath, 0, dataAfterDelete);
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		})
		uni.reLaunch({
			url: '/pages/stationManage/stationManage'
		})
	}



	const deleteStation = async (card) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除么',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success(res) {
				if (res.confirm) {
					doDelete(card)
				} else if (res.cancel) {

				}
			}
		})
	}


	const readExcel = () => {
		//选择文件
		const filePicker = uni.requireNativePlugin('Ba-FilePicker')
		filePicker.selectFile({
			'selectType': 0,
			'maxCount': 1,
			'filetypes': 'xlsx,xls'
		}, (ret) => {
			if (ret.data) {
				//解析文件
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => { //请求文件系统
					fs.root.getFile(
						ret.data[0].absolutePath, //请求文件的地址
						{
							create: false //当文件不存在时创建
						}, fileEntry => {
							fileEntry.file(function (file) {
								//new一个可以用来读取文件的对象fileReader
								let fileReader = new plus.io.FileReader();
								// fileReader.readAsText(file, "utf-8");
								fileReader.readAsDataURL(file)
								fileReader.onerror = e => { //读文件失败
									console.log("获取文件失败", fileReader.error);
									plus.nativeUI.toast("获取文件失败,请重启应用", {
										background: "#ffa38c",
										duration: 2000
									});
									return;
								};

								fileReader.onload = e => { //读文件成功
									console.log("读取excel成功");
									const model = /.*base64,/
									const newFile = e.target.result.replace(model, '');
									const workbook = XLSX.read(newFile, {
										type: 'base64'
									})
									saveBatch(workbook.Sheets.Sheet1)
									plus.nativeUI.toast('导入成功', {
										background: "#ffa38c",
										duration: 2000
									})
								};
							});
						}, error => {
							console.log("2新建获取文件失败", error);
							plus.nativeUI.toast("获取文件失败,请重启应用", {
								background: "#ffa38c",
								duration: 2000
							});
							return;
						});
				},
					e => {
						console.log("1请求文件系统失败", e.message);
						plus.nativeUI.toast("请求系统失败,请重启应用", {
							background: "#ffa38c",
							duration: 2000
						});
						return;
					}
				);
			}
		});
	}


	const goToStationDetail = (station) => {
		uni.navigateTo({
			url: `/pages/stationDetail/stationDetail?item=${encodeURIComponent(JSON.stringify(station))}`,
		})
	}

	const saveBatch = async (sheet) => {
		let cl = sheet["!ref"]
		let index = cl.indexOf(":");
		let max = parseInt(cl.substr(index + 2, cl.length))
		let array = stationCard.value


		let manuPath = '_doc/test/manufacturers.json'
		let manuData = await getJsonData(manuPath)
		let manuList = []
		if (manuData !== '') {
			manuList = JSON.parse(manuData);
		}

		for (let i = 2; i <= max; i++) {
			let obj = {}
			for (let j = 1; j <= 5; j++) {
				if (j == 1) {
					obj.stationName = sheet["A" + i.toString()]["v"]
				}
				if (j == 2) {
					obj.stationAddress = sheet["B" +
						i.toString()]["v"]
				}
				if (j == 2) {
					obj.status = sheet["C" + i.toString()]["v"] === '已调试' ? 1 : 2
				}
				if (j == 4) {
					obj.netStatus = sheet["D" + i.toString()]["v"] === '良好' ? 1 : 2
				}
				if (j == 5) {
					obj.manufacturersName = sheet["E" + i.toString()]["v"]
					let manu = manuList.find(item => item.manufacturersName === obj.manufacturersName)
					if (manu === undefined) {
						continue
					} else {
						obj.gatewayData = manu.gatewayData
						obj.videoData = manu.videoData
					}
				}
			}
			obj.stationId = Math.random().toString().slice(2, 10);
			array.push(obj)
			console.log('array', array);
		}
		let filePath = '_doc/test/station.json'

		const change = await changeData(filePath, 0, array);
		uni.showToast({
			title: '添加成功',
			icon: 'none'
		});
		uni.reLaunch({
			url: '/pages/stationManage/stationManage'
		})
	}

	const importStation = async () => {
		readExcel()
	}

	const selectTab = (tab) => {
		const index = tabs.indexOf(tab);
		selectedTabs.value = index
		if (index !== -1) {
			activeTab.value = tab;
			activeTabIndex.value = index;
		}
	}
</script>

<style lang="less">
	.flex-center {
		display: flex;
		margin-left: 10px;
	}

	.container-station {
		background: #F7F7F7;
		padding-bottom: 20px;
	}

	.header {
		padding-top: 50px;
		display: flex;
		justify-content: space-around;
		align-items: center;
		// margin: 0 20px;
	}

	.header-title {
		font-family: Source Han Sans SC;
		font-weight: 400;
		font-size: 18px;
		color: #666666;

	}

	.header-search {
		// border: 1px solid red;
		display: flex;
		align-items: center;
		justify-content: center;
	}



	.icon {
		width: 20px;
		// height: 20px;
	}

	.inputField-station {
		background-color: #fff;
		text-align: left;
		padding: 10px;

		border-radius: 5px;
		font-size: 14px;

	}


	.header-btn {
		// margin-top: 20px;
		// width: 100px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 10px;
		background-color: #48b0b1 !important;
		position: relative;
	}

	.header-btn2 {
		// margin-top: 20px;
		// width: 100px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 10px;
		background-color: #5E77F6 !important;
		position: relative;
	}

	.icon-box {
		width: 15px;
		height: 15px;
		display: flex;
		justify-content: center;
		align-items: center;

	}

	.icon {
		width: 100%;
		height: 100%;
	}

	.btn-text {
		font-size: 14px;
		margin-left: 10px;
	}

	.header-text {
		display: flex;
		align-items: center;
		background-color: #5a79ff;
		position: relative;
	}

	/* Tab 栏样式 */
	.tab-container {
		// border: 1px solid red;
		margin: 0 20px;
		display: flex;
		justify-content: space-around;
		// width: 100%;
		position: relative;

		.tab {
			padding: 10px 0;
			cursor: pointer;
			color: #aaa;
			transition: color 0.3s ease;
			font-size: 16px;

			&.active {
				color: #5dc7c8;
			}
		}

		.tab-indicator {
			position: absolute;
			bottom: 0;
			left: 0;
			height: 2px;
			background-color: #5dc7c8;
			width: calc(100% / 3);
			transition: left 0.3s ease;
		}
	}

	.content-box {
		display: flex;
		justify-content: center;
	}

	.content {
		margin-top: 20px;
		padding: 20px;
		background-color: #fff;
		// border: 1px solid #ccc;
		border-radius: 5px;
		width: 95%;
		text-align: left;
	}

	/* 卡片样式 */
	.card {
		margin-bottom: 20px;
		padding: 20px;
		// border: 1px solid #ccc;
		border-radius: 5px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;

		&.odd {
			background-color: #f3fbfb;
			/* 单数卡片背景色为绿色 */
		}

		&.even {
			background-color: #f7f7f7;
			/* 双数卡片背景色为红色 */
		}

		.tag-box {
			display: flex;
			// justify-content: center;
			align-items: center;

		}

		h3 {
			margin-left: 10px;
			font-size: 18px;
			color: #333;
		}

		p {
			margin: 10px 0 0 0;
			font-size: 16px;
			color: #666;
			// width: 450px;
		}

		.card-button {
			width: 70px;
			margin-right: 10px;
			background-color: #48b0b1;
			color: white;
			border: none;
			border-radius: 5px;
			// padding: 5px 10px;
			cursor: pointer;
			font-size: 14px;
		}

		.card-button2 {
			width: 70px;
			margin-right: 0;
			background-color: #f44336;
			color: white;
			border: none;
			border-radius: 5px;
			// padding: 5px 10px;
			cursor: pointer;
			font-size: 14px;
		}

		// .card-button:hover {
		// 	background-color: #21a0c0;
		// }
	}


	label {
		position: relative;
	}

	#fileinp {
		position: absolute;
		left: 0;
		top: 0;
		opacity: 0;
	}

	#btn {
		margin-right: 5px;
	}

	#text {
		color: red;
	}
</style>